<template>
  <div class="app-container ware-box">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              v-hasPermi="['wm:warehouses:add']"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              v-hasPermi="['wm:warehouses:export']"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              v-hasPermi="['wm:warehouses:print']"
              plain
              icon="el-icon-s-platform"
              size="mini"
              @click="handlePrint"
              >打印</el-button
            >
          </el-col>
        </el-row>
        <!-- 仓库数据 -->
        <el-table
          :data="wareList"
          border
          v-loading="loading"
          :height="maxHeight"
          ref="startPrint"
        >
          <el-table-column label="仓库代码" align="center" sortable prop="code">
          </el-table-column>
          <el-table-column label="仓库名称" align="center" prop="name">
          </el-table-column>
          <el-table-column
            label="仓库料品"
            align="center"
            prop="sortName"
            width="250"
          />
          <el-table-column label="入库类型" align="center" prop="inTypeName" />
          <el-table-column label="出库类型" align="center" prop="outTypeName">
          </el-table-column>
          <el-table-column label="仓库期间" align="center" prop="period">
            <template slot-scope="scope">
              <span v-if="scope.row.period == 0">{{
                scope.row.period | filPeriod
              }}</span>
              <span v-else>{{ scope.row.period }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="启动货位"
            align="center"
            prop="enableLocation"
            width="100"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                v-hasPermi="['wm:location:add']"
                :disabled="scope.row.enableLocation == 0"
                class="set-up"
                @click="handleLocation(scope.row)"
              >
                设置</el-button
              >
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            prop="createDate"
            sortable
          >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding"
          >
            <template slot-scope="scope">
              <div class="public-btn">
                <el-button
                  size="mini"
                  type="text"
                  v-hasPermi="['wm:warehouses:view']"
                  class="basic-see"
                  @click.stop="handleSee(scope.row)"
                  >查看
                </el-button>
                <el-button
                  size="mini"
                  class="basic-update"
                  v-hasPermi="['wm:warehouses:edit']"
                  type="text"
                  @click.stop="handleUpdate(scope.row)"
                  >修改
                </el-button>
                <el-button
                  size="mini"
                  v-hasPermi="['wm:warehouses:remove']"
                  style="color: #f56c6c"
                  class="basic-delete"
                  type="text"
                  @click.stop="handleDelete(scope.row)"
                  >删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 打印数据 -->
        <PrintPage :printData="printData" ref="startPrint" />
      </el-col>
    </el-row>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" @close="close">
      <el-form
        ref="form"
        :model="houseForm"
        label-width="80px"
        :rules="rules"
        :disabled="butChange == 'seeStatus'"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库代码" prop="code">
              <el-input
                v-model="houseForm.code"
                :disabled="this.butChange == 'updateStatus'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="name">
              <el-input v-model="houseForm.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="仓库料品" prop="sortId">
              <el-select
                v-model="selectMaterials"
                class="select-box"
                ref="materials"
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="houseChange"
              >
                <el-option
                  v-for="item in optionsMaterials"
                  :key="item.value"
                  :label="item.sortName"
                  :value="item.sortId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="入库类型" prop="inType">
              <el-select
                v-model="selectInType"
                multiple
                placeholder="请选择"
                ref="inType"
                style="width: 100%"
                @change="inTypeChange"
              >
                <el-option
                  v-for="item in optionsInType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="出库类型" prop="outType">
              <el-select
                v-model="selectOutType"
                ref="outType"
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="outTypeChange"
              >
                <el-option
                  v-for="item in optionsOutType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
            <el-col :span="24">
            <el-form-item label="到货类型" prop="arrivalType">
              <el-select
                v-model="selectArrivalType"
                ref="outType"
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="arrivalTypeChange"
              >
                <el-option
                  v-for="item in optionsArrivalType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" class="period-data">
            <el-form-item label="仓库期间">
              <el-radio-group v-model="houseForm.period" @change="periodChange">
                <el-radio label="0">自然月</el-radio>
                <el-radio label="data">固定日</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="开始期间" prop="startPeriod">
              <el-date-picker
                class="ware-editor"
                type="month"
                :clearable="false"
                placeholder="请选择"
                v-model="startPeriod"
                @change="startPeriodChange"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="periodShow">
            <el-form-item prop="periodData" label="截止日">
              <el-input v-model="houseForm.periodData" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="启动货位">
              <el-radio-group v-model="houseForm.enableLocation">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表单配置" prop="formConfig">
              <el-input v-model="houseForm.formConfig" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓管员" prop="warehouseMgr">
              <el-select
                v-model="selectKeeper"
                ref="keeper"
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="keeperChange"
              >
                <el-option
                  v-for="item in optionsKeeper"
                  :key="item.user_name"
                  :label="item.nick_name"
                  :value="item.user_name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作员" prop="warehouseOper">
              <el-select
                v-model="selectOperator"
                ref="operator"
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="operatorChange"
              >
                <el-option
                  v-for="item in optionsOperator"
                  :key="item.user_name"
                  :label="item.nick_name"
                  :value="item.user_name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="butChange !== 'seeStatus'">
        <el-button
          type="primary"
          v-if="butChange == 'addStatus'"
          @click="submitForm('form')"
          >确定</el-button
        >
        <el-button
          type="success"
          v-if="butChange == 'updateStatus'"
          @click="submitForm('form')"
          >保存</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="货位设置" :visible.sync="setLocationStatus" width="600px">
      <SetupLocation :whCode="whCode" :whName="whName" :key="locationKey" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listWarehouses,
  materialSort,
  addWarehouses,
  updateWarehouses,
  delWarehouses,
  mgrOperator,
  inOutType,
  exportWarehouses,
} from "../../api/warehouses";
import { isSerial } from "@/utils/cingsoft";
import PrintPage from "../../components/Warehouses/print"; //分类组件
//并行请求仓库料品 操作员 仓管员
import axios from "axios";
import print from "print-js"; //打印js
//货位设置组件
import SetupLocation from "../../components/Warehouses/setupLocation"; //分类组件
export default {
  name: "Warehouses",
  data() {
    //材料大类效验
    var checkSortId = (rule, value, callback) => {
      if (this.selectMaterials.length == 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    //入库类型效验
    var checkInType = (rule, value, callback) => {
      if (this.selectInType.length == 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    //出库类型效验
    var checkOutType = (rule, value, callback) => {
      if (this.selectOutType.length == 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    //仓库区间指定日
    var checkPeriod = (rule, value, callback) => {
      if (value > 31 || !value || value <= 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    //开始期间
    var checkStartPeriod = (rule, value, callback) => {
      if (this.startPeriod == null) {
        console.log(value);
        return callback(new Error(""));
      } else {
        callback();
      }
    };

    //仓管员效验
    var checkMgr = (rule, value, callback) => {
      if (this.selectKeeper.length == 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };
    //操作员效验
    var checkOper = (rule, value, callback) => {
      if (this.selectOperator.length == 0) {
        return callback(new Error(""));
      } else {
        callback();
      }
    };

    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 最大高度
      maxHeight: null,
      // 仓库查询参数
      warehouseQuery: {
        invoiceType: "",
        bredVouch: "",
        workType: "",
      },
      //仓库数据
      wareList: [],
      //打印数据
      printData: [],
      //打印状态
      printShow: false,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 表单
      value1: true,
      value2: false,
      houseForm: {
        sortId: [],
        period: "0",
        enableLocation: "0",
        periodData: "",
        startPeriod: null,
        formConfig: "",
      },
      // 仓库区间指定日
      periodShow: false,
      //开始期间
      startPeriod: null,
      // 仓库材料
      optionsMaterials: [],
      selectMaterials: [],
      //仓管员
      optionsKeeper: [],
      selectKeeper: [],
      //操作员
      optionsOperator: [],
      selectOperator: [],
      //入类类型
      optionsInType: [],
      selectInType: [],
      //出类类型
      optionsOutType: [],
      selectOutType: [],
         //到货类型
      optionsArrivalType: [],
      selectArrivalType: [],
      //弹框提交按钮状态，1（新增） 2（修改）
      butChange: "",
      //设置货位状态
      setLocationStatus: false,
      // 刷新组件
      locationKey: "",
      //仓库代码 查询货位树
      whCode: "",
      //仓库名称
      whName: "",
      // 表单校验
      rules: {
        code: [
          {
            required: true,
            message: "仓库编码不能为空",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "仓库名称不能为空",
            trigger: "blur",
          },
        ],
        sortId: [
          {
            required: true,
            validator: checkSortId,
            trigger: "change",
          },
        ],
        warehouseMgr: [
          {
            required: true,
            validator: checkMgr,
            trigger: "change",
          },
        ],
        warehouseOper: [
          {
            required: true,
            validator: checkOper,
            trigger: "change",
          },
        ],
        inType: [
          {
            required: true,
            validator: checkInType,
            trigger: "change",
          },
        ],
        outType: [
          {
            required: true,
            validator: checkOutType,
            trigger: "change",
          },
        ],
        periodData: [
          {
            required: true,
            validator: checkPeriod,
            trigger: "blur",
          },
        ],
        startPeriod: [
          {
            required: true,
            validator: checkStartPeriod,
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    //初始化仓库列表
    this.getHouselList();
  },

  methods: {
    /** 获取仓库数据 */
    getHouselList() {
      this.loading = true;
      listWarehouses(this.warehouseQuery).then((res) => {
        if (res.code == 200) {
          this.loading = false;
          this.wareList = res.rows;
          if (this.wareList.length >= 20) {
            //条数总数大于显示出现滚动条
            this.maxHeight = `${document.documentElement.clientHeight}` - 270;
          } else {
            this.maxHeight = "";
          }
        }
      });
    },

    /** 新增仓库信息*/
    handleAdd() {
      this.addUpdate()
        .then(() => {
          this.butChange = "addStatus";
        })
        .catch((err) => {
          this.msgError(err);
        });
    },

    // 仓库区间状态改变
    periodChange(value) {
      if (value == "data") {
        this.periodShow = true;
      } else {
        this.houseForm.periodData = undefined;
        this.periodShow = false;
      }
    },

    //开始期间改变
    startPeriodChange(value) {
      this.timeYearMoubth(value).then((date) => {
        console.log(date);
        this.houseForm.startPeriod = date;
      });
    },

    /** 导出*/
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出仓库列表?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportWarehouses(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },

    /** 打印*/
    handlePrint() {
      this.printData = this.wareList;
      setTimeout(() => {
        this.$print(this.$refs.startPrint.$refs.print);
      }, 0);
    },

    /* 查看仓库信息 */
    handleSee(row) {
      this.addUpdate()
        .then(() => {
          this.seeUpdate(row).then(() => {
            this.butChange = "seeStatus";
          });
        })
        .catch((err) => {
          this.msgError("请求失败");
        });
    },

    /** 修改仓库信息*/
    handleUpdate(row) {
      this.addUpdate()
        .then(() => {
          this.seeUpdate(row).then(() => {
            this.butChange = "updateStatus";
          });
        })
        .catch((err) => {
          this.msgError("请求失败");
        });
    },

    // 新增/修改/查看/请求公共部分
    addUpdate() {
      return new Promise((resolve, reject) => {
        let _self = this;
        //并行请求
        axios
          .all([
            materialSort(),
            mgrOperator({
              roleKey: "wm_mgr",
            }),
            mgrOperator({
              roleKey: "wm_oper",
            }),
            inOutType("wm_in_type"),
            inOutType("wm_out_type"),
              inOutType("po_checkin_type"),
          ])
          .then(
            axios.spread(function (
              resSort,
              resMgr,
              resOper,
              resInType,
              resOutType,
              resArrivalType
            ) {
              if (
                resSort.code == 200 &&
                resMgr.code == 200 &&
                resOper.code == 200 &&
                resInType.code == 200 &&
                resOutType.code == 200&&
                 resArrivalType.code == 200
              ) {
                _self.open = true;
                _self.title = "仓库信息";
                _self.optionsMaterials = resSort.data;
                _self.optionsKeeper = resMgr.data;
                _self.optionsOperator = resOper.data;
                _self.optionsInType = resInType.data;
                _self.optionsOutType = resOutType.data;
                  _self.optionsArrivalType = resArrivalType.data;
                resolve();
              } else {
                reject("获取仓库信息失败");
              }
            })
          );
      });
    },
    /*修改/查看/数据公共部分 */
    seeUpdate(row) {
      return new Promise((resolve, reject) => {
        // 字符串转整形
        let arr = row.sortId.split(",");
        let newArr = arr.map((v) => {
          return (v = parseInt(v));
        });
        this.selectMaterials = newArr; //仓库料品
        // console.log(this.optionsMaterials)
        this.selectKeeper = row.warehouseMgr.split(","); //仓管员
        this.selectOperator = row.warehouseOper.split(","); //操作员
        this.selectInType = row.inType.split(","); //入库类型
        this.selectOutType = row.outType.split(","); //出库类型
        if( row.arrivalType!==""){
           this.selectArrivalType = row.arrivalType.split(","); //到货类型
        }
        
        this.open = true;
        this.title = "仓库信息";
        this.houseForm = Object.assign({}, row); //拷贝物料信息
        this.houseForm.enableLocation = row.enableLocation.toString();
        if (row.period == -1 || row.period == 0) {
          this.houseForm.period = row.period.toString();
          this.periodShow = false;
        } else {
          this.periodShow = true;
          this.$set(this.houseForm, "periodData", this.houseForm.period);
          this.houseForm.period = "data";
        }
        let period = row.startPeriod;
        period = period.toString();
        let y = period.slice(0, 4),
          m = period.slice(4, 6);
        let ym = y + "-" + m;
        let date = new Date(ym);
        this.startPeriod = date;
        resolve();
      });
    },
    /** 选择料品大类*/
    houseChange(value) {
      this.houseForm.sortId = value.join(",");
    },

    /** 关闭selec下拉框*/
    closeSelect() {
      this.$refs.materials.blur();
      this.$refs.inType.blur();
      this.$refs.outType.blur();
      this.$refs.keeper.blur();
      this.$refs.operator.blur();
    },
    /** 选择料仓管员*/
    keeperChange(value) {
      this.houseForm.warehouseMgr = value.join(",");
    },

    /** 选择料仓管员*/
    operatorChange(value) {
      this.houseForm.warehouseOper = value.join(",");
    },

    /** 选择入库*/
    inTypeChange(value) {
      this.houseForm.inType = value.join(",");
    },

    /** 选择出库*/
    outTypeChange(value) {
      this.houseForm.outType = value.join(",");
    },
    
     /** 选择到货类型*/
    arrivalTypeChange(value) {
      this.houseForm.arrivalType = value.join(",");
    },

    /** 提交新增仓库列表表单*/
    submitForm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.butChange == "addStatus") {
            if (
              this.houseForm.periodData !== undefined &&
              this.houseForm.periodData !== ""
            ) {
              this.houseForm.period = this.houseForm.periodData;
            }
            addWarehouses(this.houseForm)
              .then((res) => {
                if (res.code == 200) {
                  this.msgSuccess("新增成功");
                  this.getHouselList();
                  this.cancel();
                }
              })
              .catch((err) => {
                this.msgError("新增失败");
              });
          } else {
            if (
              this.houseForm.periodData !== undefined &&
              this.houseForm.periodData !== ""
            ) {
              this.houseForm.period = this.houseForm.periodData;
            }
            updateWarehouses(this.houseForm)
              .then((res) => {
                //触发保存提交
                if (res.code == 200) {
                  this.getHouselList();
                  this.msgSuccess("修改成功");
                  this.open = false;
                }
              })
              .catch((err) => {
                this.msgError("修改失败");
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //删除物料
    handleDelete(row) {
      this.$confirm("确认删除", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delWarehouses(row.uniqueId);
        })
        .then((res) => {
          if (res.code == 200) {
            this.msgSuccess("删除成功");
            this.getHouselList();
            this.open = false;
          }
        });
    },

    //设置货位
    handleLocation(row) {
      this.whCode = row.code;
      this.whName = row.name;
      this.locationKey = Math.random();
      setTimeout(() => {
        this.setLocationStatus = true;
      });
    },

    //弹框取消
    cancel() {
      this.open = false;
      this.reset();
    },
    //仓库设置弹框关闭
    close() {
      this.reset();
    },

    /** 表单重置 */
    reset() {
      this.houseForm = {
        sortId: [],
        name: "",
        code: "",
        warehouseMgr: "",
        warehouseOper: "",
        period: "0",
        enableLocation: "0",
        startPeriod: null,
        periodData: undefined,
        formConfig: "",
      };
      this.selectMaterials = [];
      this.selectKeeper = [];
      this.selectOperator = [];
      this.selectInType = [];
      this.selectOutType = [];
         this.selectArrivalType = [];
      this.startPeriod = null;
      this.resetForm("form");
    },
    //时间转换年月
    timeYearMoubth(date) {
      return new Promise((resolve) => {
        let time = new Date(date),
          newYear,
          newMonth,
          newTime;
        newYear = time.getFullYear().toString();
        if (time.getMonth() + 1 >= 10) {
          newMonth = (time.getMonth() + 1).toString();
        } else {
          newMonth = "0" + (time.getMonth() + 1).toString();
        }
        newTime = newYear + newMonth;
        newTime = parseInt(newTime);
        resolve(newTime);
      });
    },
  },
  components: {
    PrintPage,
    SetupLocation,
  },
  filters: {
    filPeriod(period) {
      switch (period) {
        case -1:
          return "无";
          break;
        case 0:
          return "自然月";
          break;
        default:
          return "无";
      }
    },
  },
};
</script>
<style lang="scss">
.ware-box {
  .el-tag.el-tag--info {
    color: #1890ff;
  }
  .ware-editor {
    width: 100%;
  }
  .set-up {
    padding: 2px 5px !important;
    font-size: 12px;
  }

  .el-switch {
    display: flex;
    justify-content: center;
  }

  .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background-color: #f5f7fa;
    border-color: #999;
  }

  .el-radio {
    margin-right: 18px;
  }

  .el-radio__label {
    padding-left: 5px;
  }

  .el-radio:nth-of-type(3) {
    margin-right: 0;
  }

  .el-switch.is-disabled {
    opacity: 1;
  }

  .el-table .el-table__header-wrapper th,
  .el-table .el-table__fixed-header-wrapper th {
    height: 35px;
  }

  .el-dialog__body {
    padding-right: 15px;
    padding-bottom: 20px;
  }

  .el-input.is-disabled .el-input__inner {
    color: #333;
  }

  .el-form-item--medium .el-form-item__content {
    margin-right: 10px !important;
  }
}

.close-select {
  overflow: hidden;

  i {
    float: right;
    margin-right: 15px;
    color: #909399;
    cursor: pointer;
  }
}
</style>
